const express = require('express');
const router = express.Router();


//配置mysql数据库信息
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'yxb-blog'
});



//用户登录接口
router.post('/login', (req, res) => {
  //从请求对象中解构出参数
  const { username, password } = req.body;
  //判断请求参数是否为空
  if (username && password) {
    //连接数据库
    connection.connect();
    //执行sql语句并在回调函数中操作
    connection.query(`SELECT * from user where username="${username}"`, function (error, results) {
      //判断是否有错误
      if (error) throw error;
      
      //判断登录用户信息是否与数据库中的信息一致,这里有个坑就是,要先判断是否有该用户,不然会报错从而不会返回数据
      if (results[0] && username === results[0].username && password === results[0].password) {
        res.send({ code: 1,aid:results[0].aid, mes: '登录成功!' });
      } else {
        res.send({ code: -1, mes: '用户名或密码错误!' })
      }

    });
  } else {
    res.send({ code: 0, mes: '请求内容为空!' })
  }
})

//获取用户信息接口
router.post('/getUserInfo',(req,res)=>{
  const {aid}=req.body;
  if (aid) {
    connection.connect();
    connection.query(`SELECT * from user where aid="${aid}"`, function (error, results) {
      if (error) throw error;
      delete results[0].password;
      res.send({code:1,userInfo:results[0]})

    });
  }else{
    res.send({code:0,mes:'请求内容为空!'})
  }
})

//用户注册接口
router.post('/register',(req,res)=>{
  const {username,password,email,sex,description} =req.body;
  connection.connect();
  connection.query(`SELECT username from user where username="${username}"`, function (err, data) {
    if (data[0]) {res.send({code:-1,mes:'用户已存在!'});return false};
    connection.query(`INSERT INTO user(username,password,email,sex,description) VALUES ('${username}','${password}','${email}','${sex}','${description}'); `, function (error, results) {
      if (error) throw error;
      res.send({code:1,mes:'注册成功!'})
      console.log(results);
    });
  });


    
});



//导出模块
module.exports = router;




